package uutalk.netcloud.talk.app.ui.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.makeramen.roundedimageview.RoundedImageView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import uutalk.netcloud.talk.R;
import uutalk.netcloud.talk.app.Constants;

import uutalk.netcloud.talk.app.ui.ContentActivity;

import uutalk.netcloud.talk.base.android.BaseFragment;

import uutalk.netcloud.talk.base.mqtt.MQTTManager;
import uutalk.netcloud.talk.base.mqtt.PublishFactory;
import uutalk.netcloud.talk.base.mqtt.event.MqttMessageEvent;
import uutalk.netcloud.talk.base.mqtt.model.Publication;
import uutalk.netcloud.talk.base.util.LanguageUtil;
import uutalk.netcloud.talk.base.util.thirdpart.EventMamager;
import uutalk.netcloud.talk.base.util.thirdpart.ImageLoader;
import uutalk.netcloud.talk.base.util.thirdpart.QiNiuManager;
import uutalk.netcloud.talk.base.util.thirdpart.UserManager;
import uutalk.netcloud.talk.base.util.view.ToastUtil;
import uutalk.netcloud.talk.model.BussinessBeanFactory;
import uutalk.netcloud.talk.model.bean.AddFriendRspBean;
import uutalk.netcloud.talk.model.bean.CMDConstant;
import uutalk.netcloud.talk.model.bean.DBEntityManager;
import uutalk.netcloud.talk.model.bean.DeleteFriendRspBean;
import uutalk.netcloud.talk.model.bean.FriendInfoBean;
import uutalk.netcloud.talk.model.bean.SimpleEvent;
import uutalk.netcloud.talk.model.bean.SimpleEventType;
import uutalk.netcloud.talk.model.bean.UserInfo;

/**
 * Created by Administrator on 2017/12/15.
 */

public class UserInfoFragment extends BaseFragment {

    @BindView(R.id.person_icon)
    RoundedImageView personIcon;
    @BindView(R.id.tvName)
    TextView tvName;
    @BindView(R.id.tvPhoto)
    TextView tvPhoto;
    @BindView(R.id.tvEmail)
    TextView tvEmail;

    @BindView(R.id.btnAddFriend)
    Button btnAddFriend;

    @BindView(R.id.btnDelFriend)
    Button btnDelFriend;

    @BindView(R.id.llHistory)
    LinearLayout llHistory;

    @BindView(R.id.llTalk)
    LinearLayout llTalk;

    @BindView(R.id.btnSendMsg)
    Button btnSendMsg;

    @BindView(R.id.rl_user_info)
    RelativeLayout rl_user_info;

    private String userID;//用户id
    UserInfo userInfo = null;

    public static UserInfoFragment newInstance(String userID) {
        Bundle args = new Bundle();
        UserInfoFragment fragment = new UserInfoFragment();
        fragment.setArguments(args);
        fragment.userID = userID;
        return fragment;
    }

    @Override
    public boolean supportActionbar() {
        return true;
    }

    @Override
    public boolean isAutoBindEvent() {
        return true;
    }

    @Override
    protected int setLayoutResId() {
        return R.layout.fragment_user_info;
    }

    @Override
    protected void loadData() {

    }

    @Override
    protected void init() {
        progressHudUtil.showProgressHud();
        getTitleTV().setText(LanguageUtil.getStringById(R.string.str_user_info));
        userInfo = DBEntityManager.getUserInfoById(userID);
        if(userInfo == null){
            FriendInfoBean friendInfoBean = DBEntityManager.getFriendInfoBean(userID);
            if(friendInfoBean != null){
                userInfo = new UserInfo();
                userInfo.setPicture(friendInfoBean.getFriend_picture());
                userInfo.setName(friendInfoBean.getFriend_name());
                userInfo.setPhone("");
                userInfo.setEmail("");
            }
        }

        if(userInfo != null){
            initUser(userInfo);
        }

        //更新数据
        progressHudUtil.showProgressHud(false);
        Publication publication = PublishFactory.createPublication(BussinessBeanFactory.createGetUserInfoBean(userID));
        MQTTManager.getInstance().publish(publication);


        if(DBEntityManager.getFriendInfoBean(userID) != null){
            updateViewByStatus(0);
        } else {
            updateViewByStatus(1);
        }

    }

    @OnClick({R.id.btnAddFriend, R.id.btnSendMsg, R.id.btnDelFriend, R.id.llHistory})
    public void onViewClick(View view){
        switch (view.getId()){
            case R.id.btnAddFriend:{
                progressHudUtil.showProgressHud();
                Publication publication = PublishFactory.createPublication(BussinessBeanFactory.createAddSigleFriend(userID));
                MQTTManager.getInstance().publish(publication);
            }
            break;
            case R.id.btnSendMsg:{
                Log.e("UserInfoFragment",userInfo.toString());
                EventMamager.getInstance().postEvent(new SimpleEvent(SimpleEventType.ADD_SING_TALK, userInfo));
                finish();
            }
            break;
            case R.id.btnDelFriend:{
                AlertDialog.Builder builder = new AlertDialog.Builder(mActivity)
                        .setMessage(R.string.str_delete_friend_tip)
                        .setPositiveButton(R.string.str_sure, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                progressHudUtil.showProgressHud();
                                Publication publication = PublishFactory.createPublication(BussinessBeanFactory.createDeleteSigleFriend(userID));
                                MQTTManager.getInstance().publish(publication);
                                Log.e(TAG, "userID>> " + userID + "name>> " + userInfo.getName());
                            }
                        })
                        .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        });
                builder.show();

            } break;
            case R.id.llHistory:{
                int a = Integer.parseInt(UserManager.getInstance().getUserInfo().getUser_id());
                int b = Integer.parseInt(userID);
                String groupId = "";
                if (a > b) {
                    groupId = b + "_" + a;
                } else {
                    groupId = a + "_" + b;
                }

                Intent intent = new Intent(mActivity, ContentActivity.class);
                intent.putExtra(Constants.KEY_FRAGMENT, Constants.GROUP_HISTORY_FRAGMENT);
                intent.putExtra(Constants.KEY_UID, groupId);
                intent.putExtra(Constants.KEY_TYPE, 1);
                startActivity(intent);
            } break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMqttMsgEvent(MqttMessageEvent event) {
        Log.e(TAG, "onMqttMsgEvent(MqttMessageEvent event)" + event.getMessage());
        if(CMDConstant.ADD_SIGLE_FRIEND_RESP.equals(event.getMessage().getCmd())){
            AddFriendRspBean addFriendRspBean = JSON.parseObject(event.getMessage().toString(), AddFriendRspBean.class);
            progressHudUtil.dismissProgressHud();
            if(addFriendRspBean.isOk()){
                FriendInfoBean friendInfoBean = new FriendInfoBean(userInfo.getUser_id(), userInfo.getPicture(),userInfo.getName(),"#","0","0");
                updateViewByStatus(0);
                DBEntityManager.saveFriendInfoBean(friendInfoBean);
                EventMamager.getInstance().postEvent(new SimpleEvent(SimpleEventType.MSG_ADD_FRIEND_FINISH, friendInfoBean));
            } else {
                ToastUtil.makeToast(LanguageUtil.getStringById(R.string.add_friend_fail));
            }
        } else if(CMDConstant.DELELE_SIGLE_FRIEND_RESP.equals(event.getMessage().getCmd())){
            progressHudUtil.dismissProgressHud();
            DeleteFriendRspBean deleteFriendRspBean = JSON.parseObject(event.getMessage().toString(), DeleteFriendRspBean.class);
            if(deleteFriendRspBean.isOk()){
                updateViewByStatus(1);
                EventMamager.getInstance().postObjEvent(SimpleEventType.MSG_DELETE_FRIEND_FINISH, DBEntityManager.getFriendInfoBean(userID));
                DBEntityManager.deleteFriendInfoBean(userID);
            } else {
                ToastUtil.makeToast(deleteFriendRspBean.getError_msg());
            }
        }  else if (CMDConstant.GET_USER_INFO_RESP_CMD.equals(event.getMessage().getCmd())) {
            //把用户信息保存到本地
            //获取其它用户的信息
            userInfo = JSON.parseObject(event.getMessage().toString(), UserInfo.class);
            DBEntityManager.saveUserInfo(userInfo);
            initUser(userInfo);
        }
    }

    /**
     * status:0,是好友 1非好友
     * @param status
     */
    private void updateViewByStatus(int status){
        if(status == 0){
            //已经是好友了
            btnAddFriend.setVisibility(View.GONE);
            llTalk.setVisibility(View.VISIBLE);
            btnDelFriend.setVisibility(View.VISIBLE);
            llHistory.setVisibility(View.VISIBLE);
        } else if(status == 1){
            //不是好友
            llTalk.setVisibility(View.GONE);
            btnAddFriend.setVisibility(View.VISIBLE);
            btnDelFriend.setVisibility(View.GONE);
            llHistory.setVisibility(View.GONE);
        } else if(status == 3){
            //查看自己的信息
            llTalk.setVisibility(View.GONE);
            btnAddFriend.setVisibility(View.GONE);
            btnDelFriend.setVisibility(View.GONE);
            llHistory.setVisibility(View.GONE);

        }
    }

    private void initUser(UserInfo userInfo){
        if(userInfo != null){
            if(!TextUtils.isEmpty(userInfo.getPicture())){
                ImageLoader.loadImage(mActivity, QiNiuManager.QINIU_HOST + userInfo.getPicture(), personIcon);
            }

            if(!TextUtils.isEmpty(userInfo.getName())){
                tvName.setText(userInfo.getName());
            }

            if(!TextUtils.isEmpty(userInfo.getPhone())){
                tvPhoto.setText(userInfo.getPhone());
            }

            if(!TextUtils.isEmpty(userInfo.getEmail())){
                tvEmail.setText(userInfo.getEmail());
            }
            progressHudUtil.dismissProgressHud();
            rl_user_info.setVisibility(View.VISIBLE);
        } else {

        }
    }
}
